<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :rules="formRules"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="订单号" prop="orderNo">
        <el-input
          v-model="queryParams.orderNo"
          placeholder="请输入订单号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="用户编号" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入用户编号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="联系人" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入联系人姓名"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="电话" prop="userPhone">
        <el-input
          v-model="queryParams.userPhone"
          placeholder="请输入联系电话号码"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="详细地址" prop="address">
        <el-input
          v-model="queryParams.address"
          placeholder="请输入详细地址"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="物品类型" prop="itemTypeId">
        <el-cascader
          v-model="queryParams.itemTypeId"
          :options="itemTypeTree"
          :props="cascaderProps"
          placeholder="请选择回收物品类型"
          clearable
          :show-all-levels="false"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="物品描述" prop="itemDesc">
        <el-input
          v-model="queryParams.itemDesc"
          placeholder="请输入物品描述"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="预约时间" prop="appointmentTime">
        <el-date-picker
          v-model="queryParams.appointmentTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="回收人员" prop="collectorId">
        <el-select
          v-model="queryParams.collectorId"
          placeholder="请选择回收人员"
          filterable
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="item in collectorOptions"
            :key="item.id"
            :label="`${item.name}`"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="订单状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择订单状态"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.RECYCLING_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="备注信息" prop="remarks">
        <el-input
          v-model="queryParams.remarks"
          placeholder="请输入备注信息"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['recycl:order:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['recycl:order:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="订单编号" align="center" prop="id" />
      <el-table-column label="订单号" align="center" prop="orderNo" />
      <el-table-column label="用户编号" align="center" prop="userId" />
      <el-table-column label="联系人" align="center" prop="userName" />
      <el-table-column label="电话" align="center" prop="userPhone" />
      <el-table-column label="详细地址" align="center" prop="address" />
      <el-table-column label="物品类型" align="center" min-width="120px">
        <template #default="scope">
          <span>{{ formatItemType(scope.row.itemTypeId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="物品描述" align="center" prop="itemDesc" />
      <el-table-column
        label="预约时间"
        align="center"
        prop="appointmentTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="回收人员" align="center" min-width="140px">
        <template #default="scope">
          <span>{{ formatCollector(scope.row.collectorId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="订单状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.RECYCLING_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="备注信息" align="center" prop="remarks" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['recycl:order:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['recycl:order:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <OrderForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { OrderApi, OrderVO } from '@/api/recycl/order'
import OrderForm from './OrderForm.vue'
import { ItemTypeApi } from '@/api/recycl/Itemtype' // 确保路径正确
import { handleTree } from '@/utils/tree'
import { CollectorApi } from '@/api/recycl/collector'
/** 回收订单 列表 */
defineOptions({ name: 'Order' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const collectorOptions = ref<any[]>([]) // 存储回收人员选项
const loading = ref(true) // 列表的加载中
const list = ref<OrderVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  orderNo: undefined,
  userId: undefined,
  userName: undefined,
  userPhone: undefined,
  address: undefined,
  itemTypeId: undefined,
  itemDesc: undefined,
  appointmentTime: [],
  collectorId: undefined,
  status: undefined,
  remarks: undefined,
  createTime: [],
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const itemTypeTree = ref<any[]>([]) // 存储树形分类数据
const cascaderProps = {
  value: 'id',
  label: 'name',
  checkStrictly: true, // 允许选择任意层级
  emitPath: false, // 仅返回最后一级的值
  expandTrigger: 'hover' // 鼠标悬停展开
}
const formRules = reactive({
  userPhone: [
    { required: true, message: '联系电话不能为空', trigger: 'blur' },
    {
      pattern: /^(?:(?:\+|00)86)?1[3-9]\d{9}$/,
      message: '请输入有效的手机号码',
      trigger: 'blur'
    }
  ],
})
const loadCollectors = async () => {
  try {
    const { list } = await CollectorApi.getCollectorPage({
      pageNo: 1,
      pageSize: 100,  // 获取全量数据
      status: 0       // 可选：只显示在岗人员
    })
    collectorOptions.value = list
  } catch (e) {
    console.error('加载回收人员失败:', e)
    message.error('回收人员数据加载失败')
  }
}

const formatItemType = (id: number) => {
  const findName = (nodes: any[]): string => {
    for (const node of nodes) {
      if (node.id === id) return node.name
      if (node.children) {
        const found = findName(node.children)
        if (found) return found
      }
    }
    return ''
  }
  return findName(itemTypeTree.value) || id
}

const formatCollector = (id: number) => {
  const collector = collectorOptions.value.find(item => item.id === id)
  return collector ? `${collector.name}` : id
}

const loadItemTypes = async () => {
  try {
    const data = await ItemTypeApi.getItemTypeList({})
    itemTypeTree.value = handleTree(data, 'id', 'parentId')
  } catch (e) {
    console.error('加载物品分类失败:', e)
  }
}
/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await OrderApi.getOrderPage(queryParams)
    list.value = data.list
    total.value = data.total
    console.log(data)
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await OrderApi.deleteOrder(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await OrderApi.exportOrder(queryParams)
    download.excel(data, '回收订单.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
  loadCollectors()
  loadItemTypes() // 新增分类数据加载
})
</script>
